<template>
  <div class="managePapermain">
    <!-- <page-header-wrapper :breadcrumb="[]" title="问卷管理" /> -->
    <a-card>
        <span class="line">问卷管理</span>
    </a-card>
    <div style="height: 24px"></div>
    <a-spin :spinning="loading">
        <a-card>
            <template v-if="apps.length != 0">
                <div class="content" v-for="(item, index) in apps" :key="index">
                    <div class="apps">
                        <div class="ct-apps">
                            <img :src="item.avatarUrl" alt="">
                            <span>
                                {{item.name}}
                            </span>
                            <i style="margin-left: 20px; font-size: 12px; color: #1890ff; cursor: pointer;"
                                @click="() => checkKeyWords(item)"
                            >
                                关键词设置
                            </i>
                            
                        </div>
                        <div class="ct-papers">
                            <div :style="{ borderBottom: '1px solid #E9E9E9' }">
                                <a-checkbox :indeterminate="indeterminate" :checked="checkAll" @change="e => onCheckAllChange(e, item, index)">
                                    全选
                                </a-checkbox>
                            </div>
                            <br />
                            <a-checkbox-group :value="item.relatedPapers.map(i => `${i.paperId}`)" :options="plainOptions" @change="checkedValue => onChange(checkedValue, item, index)" />
                        </div>
                        <div class="ct-replays">
                            <span class="ct-replays-tips">有新粉丝关注时，会自动发送一下消息。（关联题目，会提示相应的问题）</span>
                            <div class="ct-replays-content">
                                <a-textarea :auto-size="{ minRows: 1, maxRows: 25 }" placeholder="Basic usage" v-model="item.replyMsg[0]" autosize="true" style="width: 580px"/>
                                <div v-for="(item, index) in item.relatedPapers" :key="index">
                                    &nbsp;&nbsp;{{index+1}}、{{item.title}}
                                </div>
                                <a-textarea :auto-size="{ minRows: 1, maxRows: 25 }" placeholder="Basic usage" v-model="item.replyMsg[2]" style="width: 580px"/>
                            </div>
                        </div>
                        <div class="ct-save">
                            <a-button type="primary" @click="saveAppInfo(item)">保存</a-button>
                        </div>
                    </div>
                </div>
            </template>
            <div v-else>
                <a-alert message="你还没有授权公众号 请先授权" type="warning" show-icon />
            </div>

            <a-divider :dashed="true"/>
            <a-button @click="onAddApp" style="width: 200px" type="danger">添加授权新的公众号</a-button>
        </a-card>
    </a-spin>
    <a-modal v-model="visible" title="关键词设置" @ok="handleOk" width="720px">
        <a-spin :spinning="visibleLoading">
            <div v-for="(item, index) in keyWordsApp.keywords" :key="index">
                <span>
                    {{item.title}}
                </span>
                <span style="margin: 0 20px">
                    <a-input style="width: 200px" :value="item.keywords.join(';')" @change="e => writeTextKeyWords(e, item)" />
                </span>
                <span>
                    <a-button type="danger" @click="() => clickSetKeyWords(item, keyWordsApp)">设置</a-button>
                </span>
            </div>
        </a-spin>
    </a-modal>
  </div>
</template>


<script>
import { fetchPaperList, fetchAppInfo, relatedPaper, setReply, getKeywords, postKeywords } from '@/api/paper'
// import { PageHeaderWrapper } from '@ant-design-vue/pro-layout'
import axios from 'axios'

export default {
    name: 'UserPaper',
    components: {
        // PageHeaderWrapper
    },
    data () {
        return {
            visible: false,
            visibleLoading: false,
            keyWordsApp: {},
            loading: false,
            apps: [],
            papers: [],
            plainOptions: [],
            checkedList: [],
            indeterminate: true,
            checkAll: false,
        }
    },
    methods: {
        checkKeyWords(app) {
            this.visible = true
            this.visibleLoading = true
            console.log(this.papers)
            this.keyWordsApp = {...app}
            const _this = this
            console.log(app)
            getKeywords({
                appid: app.appid
            })
                .then(res => {
                    if (res.code == 200) {
                        const newList = []
                        console.log(res.keyWordsList)
                        _this.papers.forEach(i => {
                            newList.push({
                                'paperId': i.paperId,
                                'keywords' : [],
                                'title' : i.title
                            })
                            // i.paperId == k.paperId ? [...k.keywords] : 
                        })
                        res.keyWordsList.forEach(k => {
                            newList.forEach((i, index) => {
                                if (i.paperId == k.paperId) {
                                    newList[index] = {
                                        'paperId': i.paperId,
                                        'keywords' : [...k.keywords],
                                        'title' : i.title
                                    }
                                }
                            })
                        })
                        this.keyWordsApp = {...app, keywords: [...newList]}
                        console.log(this.keyWordsApp)
                        _this.visibleLoading = false
                        // this.keyWordsApp = {...app, keywords: [...res.keyWordsList]}
                        // _this.visibleLoading = false

                    } else {
                        _this.$message.error(res.errormsg)
                    }
                })
            // const getKeywords = [{
					// "paperId":"ee499b32cbd000",
					// "keywords":['测试1','牛逼'],
                    // "title": '哈哈哈哈哈哈哈'
			// 	},
			// 	{
			// 		"paperId":"ee499b32cbd002",
			// 		"keywords":['测试2'],
            //         "title": 'heiheihei'
			// 	}
			// ]
        },
        writeTextKeyWords(e, item) {
            const value = e.currentTarget.value
            const id = item.paperId
            this.keyWordsApp.keywords.forEach((i, index) => {
                if (i.paperId == id) {
                    this.keyWordsApp.keywords[index].keywords = value.split(';')
                }
            })
        },
        clickSetKeyWords(item, app) {
            const _this = this
            this.visibleLoading = true
            postKeywords({
                appid: app.appid,
                paperId: item.paperId,
                keywords: [...item.keywords]
            }).then(i => {
                if (i.code && i.code == 200) {
                    _this.$message.success(i.msg)
                } else {
                    _this.$message.error(i.errormsg)
                }
                _this.visibleLoading = false
            })
        },
        onChange(checkedList, app, index) {
            const newCheck = []
            checkedList.forEach(i => {
                this.papers.forEach(k => {
                    if (k.paperId == i) {
                        newCheck.push({
                            paperId: k.paperId, title: k.title
                        })
                    }
                })
            })
            this.apps[index].relatedPapers = [...newCheck]
            this.indeterminate = !!checkedList.length && checkedList.length < this.plainOptions.length;
            this.checkAll = checkedList.length === this.plainOptions.length;
        },
        onCheckAllChange(e, app, index) {
            Object.assign(this, {
                // checkedList: e.target.checked ? this.papers.map(i => `${i.paperId}`) : [],
                indeterminate: false,
                checkAll: e.target.checked,
            });
            this.apps[index].relatedPapers = e.target.checked ? this.papers.map(i => {return {paperId: i.paperId, title: i.title}}) : []
        },
        // 授权按钮
        onAddApp() {
            const _this = this
            _this.loading = true
            axios.get("http://login.comeonfans.com/web/authcode", {
                    headers: {
                        'Accept': 'application/json;application/json',
                        'Content-Type': 'application/json;charset=UTF-8;'
                    }
                })
                    .then(res => {
                        if (res.status === 200 && res.data['msg'] === 'ok') {
                            window.open(res.data.url, "_blank");
                            _this.loading = false
                        } else {
                            alert('err')
                        }
                    })
        },
        // 保存app信息
        saveAppInfo(app) {
            const _this = this
            // 先关联问卷 后保存回复信息
            _this.loading = true
            const hide = this.$message.loading('正在保存，请稍后...', 0);
            relatedPaper({
                appid: app.appid,
                paperId: app.relatedPapers.map(v => v.paperId)
            })
                .then(res => {
                    if (res.code == 200) {  // 关联问卷成功
                        setReply({
                            appid: app.appid,
                            replyMsg: [app.replyMsg[0], 'insert', app.replyMsg[2]]
                        })
                            .then(res => {
                                if (res.code == 200) {  // 设置自动回复成功
                                    this.$message.success('保存成功')
                                } else {
                                    this.$message.error('设置自动回复失败，请重新尝试')
                                }
                                 _this.loading = false
                                hide()
                            })
                    } else {
                        _this.loading = false
                        hide()
                        this.$message.error('关联问卷失败，请重新尝试')
                    }
                })
        },
        init() {
            const _this = this
            _this.loading = true
            // 获取关联的公众号信息
            fetchAppInfo()
                .then(res => {
                    if (res && res.code == 200) {
                        // 获取app成功
                        _this.apps = res.data.apps
                        // 获取该用户的paper列表
                        fetchPaperList()
                            .then(res => {
                                console.log(res)
                                if (res && res.code == 200) {
                                    _this.loading = false
                                    // _this.apps.papers = res.data.papers
                                    res.data.papers.forEach(i => {
                                        _this.$nextTick(() => {
                                            _this.plainOptions.push({
                                                label: i.title,
                                                value: i.paperId
                                            })
                                        })
                                        
                                    })
                                    _this.papers = res.data.papers

                                } else {
                                    // 失败
                                    _this.$message.error('获取信息失败，请刷新页面重新尝试')
                                    _this.loading = false
                                }
                            })
                    } else {
                        // 失败
                        _this.$message.error('获取信息失败，请刷新页面重新尝试')
                        _this.loading = false
                    }
                })
        }
    },
    mounted: function () {
        this.init()
    }
}
</script>

<style lang="less" scope>
    
    .managePapermain {
        position: relative;
        width: 100%;
        .line {
            border-left: 5px solid #1890ff;
            padding-left: 10px;
            font-weight: 500;
            font-size: 16px;
        }
        .content {
            position: relative;
            margin-top: 24px;
            display: flex;
            flex-wrap: wrap;
            min-height: 100px;
            flex-direction: column;
            .apps {
                position: relative;
                display: flex;
                flex-direction: column;
                .ct-apps {
                    position: relative;
                    display: flex;
                    align-items: center;
                    img {
                        width: 68px;
                        height: 68px;
                        border-radius: 50%;
                        margin-right: 28px;
                    }
                    span {
                        font-size: 20px;
                        font-weight: 400;
                        color: #000;
                        font-family: '微软雅黑'
                    }
                }
                .ct-papers {
                    margin: 24px 0;
                }
                .ct-replays {
                    margin-bottom: 24px;
                    padding: 10px;
                    border: 1px solid #eee;
                    .ct-replays-tips {
                        color: #949494;
                        font-size: 13px;
                        margin-bottom: 5px;
                    }
                    /deep/ .ant-input:placeholder-shown {
                        border: none
                    }
                    /deep/ .ant-input {
                        border: none
                    }
                }


            }
        }
        /deep/ .ant-checkbox-group {
            position: relative;
            flex-direction: column;
            max-height: 100px;
            flex-wrap: wrap;
            display: flex;
            width: auto;
            width: 170px;
            /deep/ .ant-checkbox-group-item {
                width: 170px;
                margin-top: 10px;
                display: block;
            }
        }
    }
    

    
</style>